<!-- 商品管理 -->
<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 部门树 -->
      <el-col :lg="4" :xs="24" class="mb-[12px]">
        <CategoryTree
          ref="categoryTreeRef"
          v-model="queryParams.categoryIds"
          @node-click="handleQuery"
        />
      </el-col>

      <!-- 商品列表 -->
      <el-col :lg="20" :xs="24">
        <!-- 搜索区域 -->
        <div class="search-container">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="auto">
            <el-form-item label="关键字" prop="keywords">
              <el-input
                v-model="queryParams.keywords"
                placeholder="商品名"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>

            <el-form-item label="状态" prop="market">
              <el-select
                v-model="queryParams.market"
                placeholder="全部"
                clearable
                style="width: 100px"
              >
                <el-option label="上架" :value="true" />
                <el-option label="下架" :value="false" />
              </el-select>
            </el-form-item>

            <el-form-item class="search-buttons">
              <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
              <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-card shadow="hover" class="data-table">
          <div class="data-table__toolbar">
            <div class="data-table__toolbar--actions">
              <el-button
                type="primary"
                plain
                icon="bottom-right"
                @click="showChooseWindow('material')"
              >
                导入材料
              </el-button>
              <el-button type="primary" plain icon="files" @click="showChooseWindow('saleMeal')">
                导入套餐
              </el-button>
              <el-button
                type="danger"
                icon="delete"
                :disabled="selectIds.length === 0"
                @click="handleDelete()"
              >
                删除
              </el-button>
            </div>
          </div>

          <el-table
            v-loading="loading"
            :data="pageData"
            border
            stripe
            highlight-current-row
            class="data-table__content"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="编码" width="150" align="center" prop="code" />
            <el-table-column label="商品名" prop="name" />
            <el-table-column label="状态" align="center" prop="market" width="80">
              <template #default="scope">
                <el-switch
                  v-model="scope.row.market"
                  inline-prompt
                  active-text="上架"
                  inactive-text="下架"
                  @change="changeMarket(scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column label="推荐" align="center" prop="market" width="80">
              <template #default="scope">
                <el-switch
                  v-model="scope.row.hot"
                  inline-prompt
                  active-text="推荐"
                  inactive-text="默认"
                  @change="changeHot(scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column label="品牌" width="120" align="center" prop="brand" />
            <el-table-column label="型号" width="120" align="center" prop="model" />
            <el-table-column label="简介" width="150" prop="brief" />
            <el-table-column label="单位" width="70" align="center" prop="unit" />
            <el-table-column label="厂家" align="center" prop="company" width="120" />
            <el-table-column label="更新时间" align="center" prop="updateTime" width="160" />
            <el-table-column label="操作" fixed="right" width="220">
              <template #default="scope">
                <el-button
                  type="primary"
                  icon="edit"
                  link
                  size="small"
                  @click="gotoPage(scope.row.id)"
                >
                  编辑
                </el-button>
                <el-button
                  type="danger"
                  icon="delete"
                  link
                  size="small"
                  @click="handleDelete(scope.row.id)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="fetchData"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 客户表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="800px"
      @close="closeChooseWindow"
    >
      <MaterialSelector
        v-if="chooseType == 'material'"
        ref="materialRef"
        :ex-query="materialExQuery"
      />
      <SaleMealSelector
        v-if="chooseType == 'saleMeal'"
        ref="saleMealRef"
        :ex-query="materialExQuery"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="chooseChooselDone">确 定</el-button>
          <el-button @click="closeChooseWindow">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import CategoryTree from "./components/CategoryTree.vue";
import GoodsAPI, { GoodsPageQuery, GoodsPageVO } from "@/api/goods/goods.api";
import router from "@/router";
import MaterialSelector from "@/views/business/material/material/MaterialSelector.vue";
import SaleMealSelector from "@/views/business/material/sealMeal/SaleMealSelector.vue";
import MaterialAPI from "@/api/business/material/material.api";
import SealMealAPI from "@/api/business/material/sealMeal.api";

defineOptions({
  name: "Goods",
  inheritAttrs: false,
});

const materialRef = ref();
const categoryTreeRef = ref();
const saleMealRef = ref();
const queryFormRef = ref();
const chooseType = ref("material");
const queryParams = reactive<GoodsPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

const pageData = ref<GoodsPageVO[]>();
const total = ref(0);
const loading = ref(false);

const dialog = reactive({
  title: "",
  visible: false,
});

const materialExQuery = reactive({
  related: false,
  inventory: true,
});
function showChooseWindow(type: string) {
  chooseType.value = type;
  if (!queryParams.categoryIds) {
    ElMessage.warning("请选择左侧需要导入到的分类");
    return;
  }
  dialog.visible = true;
  dialog.title = type === "material" ? "选择材料" : "选择套餐";
  nextTick(() => {
    type === "material" ? materialRef.value.handleQuery() : saleMealRef.value.handleQuery();
  });
}

function closeChooseWindow() {
  dialog.visible = false;
}

const chooseChooselDone = async () => {
  let choosedArray: Array<any> = [];
  try {
    if (chooseType.value === "material") {
      choosedArray = materialRef.value.getChecked().map((item: { id: any }) => item.id);
      await MaterialAPI.transToGoods(queryParams.categoryIds || "", choosedArray);
    } else {
      choosedArray = saleMealRef.value.getChecked().map((item: { id: any }) => item.id);
      await SealMealAPI.transToGoods(queryParams.categoryIds || "", choosedArray);
    }
    ElMessage.success("导入成功");
    handleQuery();
  } catch (error) {
    ElMessage.error("导入失败");
    console.error("导入失败", error);
  } finally {
    dialog.visible = false;
  }
};

// 选中的商品ID
const selectIds = ref<number[]>([]);

function changeMarket(row: GoodsPageVO) {
  GoodsAPI.updateMarket(row.id!, !!row.market);
}

function changeHot(row: GoodsPageVO) {
  GoodsAPI.updateHot(row.id!, !!row.hot);
}

// 获取数据
async function fetchData() {
  loading.value = true;
  try {
    const data = await GoodsAPI.getPage(queryParams);
    pageData.value = data.list;
    total.value = data.total;
  } finally {
    loading.value = false;
  }
}

// 查询（重置页码后获取数据）
function handleQuery() {
  queryParams.pageNum = 1;
  if (queryParams.categoryIds) {
    queryParams.deepSearch = true;
  }
  fetchData();
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  fetchData();
}

// 选中项发生变化
function handleSelectionChange(selection: any[]) {
  selectIds.value = selection.map((item) => item.id);
}

function gotoPage(id?: string) {
  if (id) {
    router.push({
      path: "/goods/goodsEdit",
      query: { goodsId: id, title: "修改商品" },
    });
  } else {
    router.push({
      path: "/goods/goodsEdit",
      query: { title: "添加商品" },
    });
  }
}

/**
 * 删除商品
 * @param id  商品ID
 */
function handleDelete(id?: number) {
  const userIds = [id || selectIds.value].join(",");
  if (!userIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除商品?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    function () {
      loading.value = true;
      GoodsAPI.deleteByIds(userIds)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    function () {
      ElMessage.info("已取消删除");
    }
  );
}
</script>

<style lang="scss" scoped></style>
